package com.yzc.mihuyou.util;

import com.alibaba.fastjson.JSONObject;
import com.yzc.mihuyou.entity.User;
import com.yzc.mihuyou.service.UserService;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class TokenProccessor {
    private static final long EXPIRE_TIME=60*60*1000*24*7; //过期时间7天
    private static final String KEY = "huterox"; //加密秘钥
    
    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public static  String getToken(String user) {
        Map<String,Object> header = new HashMap<>();
        header.put("typ","JWT");
        header.put("alg","HS256");
        JwtBuilder builder = Jwts.builder().setHeader(header)
                .setExpiration(new Date(System.currentTimeMillis()+EXPIRE_TIME))
                .setSubject(user)//设置信息，也就是用户名
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256,KEY);//加密方式
        return builder.compact();
    }



    /**
     * 验证token是否有效
     * @param token  请求头中携带的token
     */
    public  User verify(String token){
        if(token==null){
            return null;
        }
            User user=new User();
            String userJson = stringRedisTemplate.opsForValue().get(token);
            if(userJson!=null) {
                JSONObject pa = JSONObject.parseObject(userJson);
                user.setUserId(new Long(pa.getString("userId")));
                try {
                    Claims  claims = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
                    String id;
                    try {
                        id = claims.getSubject();
                    } catch (Exception e) {
                        return null;
                    }
                    if(!pa.getString("userId").equals(id)){
                        return null;
                    }
                }catch (ExpiredJwtException e){
                    return null;
                }
                return user;
            }
        return null;
    }


}
